import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  SyncOutlined, SearchOutlined, UndoOutlined, OrderedListOutlined, CheckOutlined, FileDoneOutlined, AuditOutlined,
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  DatePicker,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Modal,
  Radio, Space,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import { use } from 'video.js/dist/types/tech/middleware';
import {
  approveVideo,
  changeVideoOrder,
  deleteVideo,
  getVideoInfoList,
} from '@/services/videoManager';
import { formatDate } from '@/utils/formatDate';
import { history, useModel } from 'umi';
import { ProForm } from '@ant-design/pro-components';
import { authorOptions, statusOptions, timeOptions } from './options';
const MediaManagement: React.FC = () => {
  const seniorRoleID = [1, 3, 5];
  const normalRoleID = [2];
  const wathcerRoleID = [4];
  const [form] = Form.useForm();
  const [approveForm] = Form.useForm();
  const [isOrder, setIsOrder] = useState(false);
  const [orderNum, setOrderNum] = useState(0);
  const [currentRow, setCurrentRow] = useState<any>();
  const [displaySbyy, setDisplaySbyy] = useState(false);
  const [currentRowValue, setCurrentRowValue] = useState();
  const [approveOpen, setApproveOpen] = useState(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [loadingTable, setLoadingTable] = useState(true);

  const redirectToDetail = (record) => {
    history.push({
      pathname:'/videoManagement/videoDetail',
      state: {
        videoForm: record,
    }
    });

  };
  const redirectToEdit = (record) => {
    history.push({
      pathname:'/videoManagement/videoEdit',
      state: {
        videoForm: record,
    }
    });
  };
  const changeApprove = (values) => {
    console.log(values);
    const currentValue = values.target.value;
    if (currentValue === '0') setDisplaySbyy(true);
    else if (currentValue === '1') setDisplaySbyy(false);
  };
  const submitApprove = async (values) => {
    const apprveFormValues = approveForm.getFieldsValue();
    if (values.sftg === '1') delete values.sbyy;
    const approveData = {
      ...values,
      id: currentRowValue?.id,
    };
    try {
      const res = await approveVideo(approveData);
      message.success('提交审核成功！');
    } catch (error) {
      message.error('提交审核失败！' + error.response.data.message);
    }

    setApproveOpen(false);
    queryData();
  };
  const handleCancel = () => {
    setApproveOpen(false);
    setDisplaySbyy(false);
  };

  const handleOrderOk = async () => {
    const params = {
      id: currentRow.id,
      pxh: orderNum,
    };
    const res = await changeVideoOrder(params);
    if (res.code == '0') {
      message.success('修改成功！');
      queryData();
    }
    setIsOrder(false);
  };

  const handleOrderCancel = () => {
    setIsOrder(false);
  };

  const onOrderChange = (e: any) => {
    setOrderNum(e.target.value);
  };
  const clickOnApprove = (record) => {
    setApproveOpen(true);
    setCurrentRowValue(record);
    const approveFormInitValues = {
      sftg: record.zt === '审核不通过' ? '0' : '1',
      sbyy: record.sbyy,
    };
    approveForm.setFieldsValue(approveFormInitValues);
  };
  const clickOnSort = (record) => {
    setCurrentRow(record);
    setIsOrder(true);
  };
  const columns: ProColumns[] = [
    {
      title: '缩略图',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'coverImage',
      render: (_, record) => [
        <img
          style={{
            width: 80,
            height: 100,
            cursor: 'pointer',
          }}
          onClick={() => {
            redirectToDetail(record);
          }}
          src={record.coverImage}
          alt=""
          srcset=""
        />,
      ],
    },
    {
      title: '主题',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'title',
    },
    {
      title: '发布者',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createBy',
    },
    {
      title: '发布时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '排序',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'pxh',
    },
    {
      title: '状态',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'zt',
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            // handleUpdateModalVisible(true);
            // setCurrentRow(record);
            redirectToEdit(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleRemoveVideo(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
        seniorRoleID.includes(currentUser.roleId)
          ? [
              <a key={3} onClick={() => clickOnSort(record)}>
                <Button  className={'buttonMargin'} shape={'round'} icon={<OrderedListOutlined />}>
                  排序
                </Button>
              </a>,
              <a onClick={() => clickOnApprove(record)}>
                <Button className={'buttonMargin'} shape={'round'} icon={<AuditOutlined />}>
                  审核
                </Button>
              </a>,
            ]
          : '',
      ],
    },
  ];
  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const handleRemoveVideo = async (record) => {
    let idArray = [];
    const hide = message.loading('正在删除');
    idArray.push(record.id);
    try {
      const res = await deleteVideo(idArray);
      queryData();
      hide();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败' + error.response.data.message);
      return false;
    }
  };
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="关键字" name="searchKey">
                <Input placeholder="请输入关键字" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="titleType">
                <Select
                  placeholder={timeOptions[0].label}
                  style={{ width: '80%' }}
                  options={timeOptions}
                  onChange={() => queryData()}
                ></Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={'zt'}>
                <Select
                  placeholder={statusOptions[0].label}
                  style={{ width: '80%' }}
                  options={statusOptions}
                  onChange={() => queryData()}
                ></Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name={'creater'}>
                <Select
                  placeholder={authorOptions[0].label}
                  style={{ width: '80%' }}
                  options={authorOptions}
                  onChange={() => queryData()}
                ></Select>
              </Form.Item>
            </Col>

            <Col
              span={8}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });

  const queryData = async () => {
    setLoadingTable(true);
    let values = form.getFieldsValue();
    Object.keys(values).map((item) => {
      if (values[item] === 'all') delete values[item];
    });
    const params = {
      page: page,
      pageSize: pageSize,
    };

    const msg = await getVideoInfoList(params, values);
    setDataArray(msg.data?.list || []);
    setPagination({ ...pagination, total: msg.data?.total });
    setLoadingTable(false);
  };

  useEffect(() => {
    queryData();
  }, [page, pageSize]);

  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        headerTitle="视媒管理"
        // actionRef={actionRef}
        loading={loadingTable}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        dataSource={dataArray}
        pagination={pagination}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              location.href = location.href.replace(/mediaManagement/, 'videoPublish');
            }}
          >
            <PlusOutlined />
            上传视频
          </Button>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              queryData();
            }}
          >
            <SyncOutlined />
            刷新
          </Button>,
        ]}
        columns={columns}
        rowSelection={
          {
            // onChange: (_, selectedRows) => {
            //     setSelectedRows(selectedRows);
            // },
          }
        }
      ></ProTable>
      <Modal open={approveOpen} title="审核" onCancel={handleCancel} footer={null}>
        <ProForm
          defaultValue={currentRowValue}
          onFinish={submitApprove}
          form={approveForm}
          onReset={() => {
            setDisplaySbyy(false);
            setApproveOpen(false);
          }}
          submitter={{
            render: (_, dom) => (
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Space>
                  {/*{dom}*/}
                  {<Button onClick={() => {
                    _.reset()
                  }}><UndoOutlined />关闭</Button>}
                  {<Button type={"primary"} onClick={() => {
                    _.submit()
                  }}><CheckOutlined />提交</Button>}

                </Space>
              </div>
            ),
          }}
        >
          <Form.Item name="sftg">
            <Radio.Group
              // defaultValue={currentRowValue && currentRowValue.zt === '审核不通过'?'0': '1'}
              options={[
                {
                  label: '通过',
                  value: '1',
                },
                {
                  label: '不通过',
                  value: '0',
                },
              ]}
              onChange={changeApprove}
            ></Radio.Group>
          </Form.Item>
          <Form.Item name="sbyy">
            <Input
              // defaultValue={}
              placeholder="请输入不通过原因"
              name="sbyy"
              style={{
                display: displaySbyy ? 'block' : 'none',
              }}
            ></Input>
          </Form.Item>
        </ProForm>
      </Modal>
      <Modal
        destroyOnClose
        title="排序"
        open={isOrder}
        onOk={handleOrderOk}
        onCancel={handleOrderCancel}
      >
        <Input placeholder="请输入排序!" onChange={onOrderChange} />
      </Modal>
    </PageContainer>
  );
};
export default MediaManagement;
